package com.neudu.glsb.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neudu.glsb.pojo.Ingredients;
import com.neudu.glsb.pojo.ProductIngredients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

@Service
public class StockService {

    // 数据库精准ID（糖浆=166，冰块=167）
    public static final Integer SYRUP_INGREDIENT_ID = 166;
    public static final Integer ICE_INGREDIENT_ID = 167;

    // 单份基础用量（确保扣减量充足）
    public static final int SINGLE_TOPPING_NEED = 50;  // 小料单份50克

    @Autowired
    private IngredientsService ingredientsService;

    @Autowired
    private ProductIngredientsService productIngredientsService;

    /**
     * 校验所有基础原料库存（含糖浆、冰块、其他原料，添加空值校验）
     */
    public String checkBaseMaterialStock(Integer productId, Integer quantity, String sweetnessCode, String iceCode) {
        // 空值校验（避免空指针）
        if (productId == null) return "商品ID不能为空";
        if (quantity == null || quantity <= 0) return "购买数量不能为空且必须大于0";
        if (sweetnessCode == null || sweetnessCode.trim().isEmpty()) sweetnessCode = "full";
        if (iceCode == null || iceCode.trim().isEmpty()) iceCode = "normal";

        // 查询商品关联的所有基础原料（含草莓、牛奶、糖浆、冰块等）
        LambdaQueryWrapper<ProductIngredients> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductIngredients::getProductId, productId);
        List<ProductIngredients> baseMaterials = productIngredientsService.list(queryWrapper);

        if (baseMaterials.isEmpty()) return "该商品未配置任何基础原料";

        for (ProductIngredients pi : baseMaterials) {
            Ingredients ingredient = ingredientsService.getById(pi.getIngredientId());
            if (ingredient == null) return "原料不存在（ID：" + pi.getIngredientId() + "）";

            // 计算基础用量（商品单份用量 × 购买份数）
            BigDecimal baseNeed = pi.getQuantityNeeded().multiply(new BigDecimal(quantity));
            BigDecimal totalNeed = baseNeed;

            // 糖浆：按甜度调整
            if (SYRUP_INGREDIENT_ID.equals(ingredient.getId())) {
                totalNeed = calculateSweetnessNeed(baseNeed, sweetnessCode);
            }
            // 冰块：按冰度调整
            else if (ICE_INGREDIENT_ID.equals(ingredient.getId())) {
                totalNeed = calculateIceNeed(baseNeed, iceCode);
            }
            // 其他原料（如草莓、牛奶）：按基础用量直接计算
            else {
                totalNeed = baseNeed;
            }

            // 库存校验（四舍五入取整）
            int needInt = totalNeed.setScale(0, RoundingMode.HALF_UP).intValue();
            if (ingredient.getStock() < needInt) {
                return ingredient.getIngredientName() + "库存不足（当前：" + ingredient.getStock() +
                        ingredient.getUnit() + "，需：" + needInt + ingredient.getUnit() + "）";
            }
        }
        return null;
    }

    /**
     * 扣减所有基础原料库存（含糖浆、冰块、其他原料）
     */
    @Transactional(rollbackFor = Exception.class)
    public void deductBaseMaterialStock(Integer productId, Integer quantity, String sweetnessCode, String iceCode) {
        // 空值校验
        if (productId == null) throw new RuntimeException("商品ID不能为空");
        if (quantity == null || quantity <= 0) throw new RuntimeException("购买数量不能为空且必须大于0");
        if (sweetnessCode == null || sweetnessCode.trim().isEmpty()) sweetnessCode = "full";
        if (iceCode == null || iceCode.trim().isEmpty()) iceCode = "normal";

        // 查询商品所有基础原料
        LambdaQueryWrapper<ProductIngredients> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductIngredients::getProductId, productId);
        List<ProductIngredients> baseMaterials = productIngredientsService.list(queryWrapper);

        if (baseMaterials.isEmpty()) throw new RuntimeException("该商品未配置任何基础原料");

        for (ProductIngredients pi : baseMaterials) {
            Ingredients ingredient = ingredientsService.getById(pi.getIngredientId());
            if (ingredient == null) throw new RuntimeException("原料不存在（ID：" + pi.getIngredientId() + "）");

            BigDecimal baseNeed = pi.getQuantityNeeded().multiply(new BigDecimal(quantity));
            BigDecimal totalNeed = baseNeed;

            // 糖浆调整
            if (SYRUP_INGREDIENT_ID.equals(ingredient.getId())) {
                totalNeed = calculateSweetnessNeed(baseNeed, sweetnessCode);
            }
            // 冰块调整
            else if (ICE_INGREDIENT_ID.equals(ingredient.getId())) {
                totalNeed = calculateIceNeed(baseNeed, iceCode);
            }

            // 扣减库存（取整，避免负数）
            int deductInt = totalNeed.setScale(0, RoundingMode.HALF_UP).intValue();
            if (ingredient.getStock() < deductInt) {
                throw new RuntimeException(ingredient.getIngredientName() + "库存不足，无法扣减");
            }
            ingredient.setStock(ingredient.getStock() - deductInt);
            ingredientsService.updateById(ingredient); // 强制更新所有原料库存
        }
    }

    /**
     * 糖浆用量计算（毫升）
     */
    private BigDecimal calculateSweetnessNeed(BigDecimal baseNeed, String sweetnessCode) {
        switch (sweetnessCode) {
            case "full": return baseNeed.multiply(new BigDecimal("1.0"));
            case "seven": return baseNeed.multiply(new BigDecimal("0.7"));
            case "five": return baseNeed.multiply(new BigDecimal("0.5"));
            case "three": return baseNeed.multiply(new BigDecimal("0.3"));
            case "zero": return BigDecimal.ZERO;
            default: return baseNeed;
        }
    }

    /**
     * 冰块用量计算（克）
     */
    private BigDecimal calculateIceNeed(BigDecimal baseNeed, String iceCode) {
        switch (iceCode) {
            case "more": return baseNeed.multiply(new BigDecimal("1.2"));
            case "less": return baseNeed.multiply(new BigDecimal("0.5"));
            case "normal": return baseNeed; // 正常冰：按基础用量
            case "warm": return BigDecimal.ZERO; // 常温：0克
            default: return baseNeed;
        }
    }

    /**
     * 校验小料库存（单份50克，足量扣减）
     */
    public String checkToppingStock(List<Map<String, Object>> selectedIngredients, Integer quantity) {
        if (quantity == null || quantity <= 0) return "购买数量不能为空且必须大于0";
        if (selectedIngredients == null || selectedIngredients.isEmpty()) return null;

        for (Map<String, Object> ingMap : selectedIngredients) {
            Integer ingredientId = (Integer) ingMap.get("ingredientId");
            if (ingredientId == null || ingredientId == -1) continue;

            Ingredients ingredient = ingredientsService.getById(ingredientId);
            if (ingredient == null) return "小料不存在（ID：" + ingredientId + "）";

            int totalNeed = SINGLE_TOPPING_NEED * quantity;
            if (ingredient.getStock() < totalNeed) {
                return ingredient.getIngredientName() + "库存不足（当前：" + ingredient.getStock() +
                        "克，需：" + totalNeed + "克）";
            }
        }
        return null;
    }

    /**
     * 扣减小料库存（单份50克）
     */
    @Transactional(rollbackFor = Exception.class)
    public void deductToppingStock(List<Map<String, Object>> selectedIngredients, Integer quantity) {
        if (quantity == null || quantity <= 0) throw new RuntimeException("购买数量不能为空且必须大于0");
        if (selectedIngredients == null || selectedIngredients.isEmpty()) return;

        for (Map<String, Object> ingMap : selectedIngredients) {
            Integer ingredientId = (Integer) ingMap.get("ingredientId");
            if (ingredientId == null || ingredientId == -1) continue;

            Ingredients ingredient = ingredientsService.getById(ingredientId);
            if (ingredient == null) throw new RuntimeException("小料不存在（ID：" + ingredientId + "）");

            int totalDeduct = SINGLE_TOPPING_NEED * quantity;
            if (ingredient.getStock() < totalDeduct) {
                throw new RuntimeException(ingredient.getIngredientName() + "库存不足，无法扣减");
            }
            ingredient.setStock(ingredient.getStock() - totalDeduct);
            ingredientsService.updateById(ingredient);
        }
    }
}